package com.sat.user.controller;

import com.alibaba.fastjson.JSON;
import com.sat.user.pojo.User;
import com.sat.user.service.UserService;
import com.sat.user.util.JwtUtil;
import entity.BCrypt;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login")
    public Result login(String username, String password, HttpServletResponse response){
        User loginUser = userService.findById(username);
        if(loginUser!=null && BCrypt.checkpw(password,loginUser.getPassword())){
            //设置令牌信息
            Map<String,Object> info = new HashMap<String,Object>();
            info.put("role","USER");
            info.put("success","SUCCESS");
            info.put("username",username);
            //生成令牌  String jwt = JwtUtil.createJWT("weiyibiaoshi", "aaaaaa", null);
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(info),null);
            Cookie cookie = new Cookie("Authorization", jwt);
            response.addCookie(cookie);
            //3.设置头文件中
            response.setHeader("Authorization",jwt);
            return new Result(true,StatusCode.OK,"登录成功！",jwt);
        }
        return  new Result(false,StatusCode.LOGINERROR,"账号或者密码错误！");
    }



}
